﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Xml;
using System.IO;
using System.Data.Common;
using System.Data.SqlClient;
using System.Data;
using System.Data.SqlTypes;

namespace TwiSQL
{
    public class Twitter
    {

        /// <summary>
        /// Send a tweet.
        /// </summary>
        /// <param name="username">Twitter account username.</param>
        /// <param name="password">Twitter account password.</param>
        /// <param name="message">The message to post to the Twitter account.</param>
        public static string SendTweet(string username, string password, string message)
        {

            try
            {
                //append a stamp to allow duplicate tweets
                string stamp = Guid.NewGuid().ToString().Substring(0, 3);
                string parameters = "status=" + message + " /" + stamp;
                return Post("http://twitter.com/statuses/update.xml", username, password, parameters);
            }
            catch(Exception ex)
            {
                return ex.Message;
            }

        }

        /// <summary>
        /// Creates a web request and posts variables.
        /// </summary>
        /// <param name="URI">Location of site to request.</param>
        /// <param name="username">Basic HTTP authorization user name.</param>
        /// <param name="password">Basic HTTP authorization password.</param>
        /// <param name="Parameters">POST variables.</param>
        /// <returns></returns>
        private static string Post(string url, string username, string password, string postParams) {
            //twitter's servers do not like the 'expect 100' headers, turn them off.
            //http://msdn.microsoft.com/en-us/library/system.net.servicepoint.expect100continue.aspx
            System.Net.ServicePointManager.Expect100Continue = false;
            WebClient wb = new WebClient();
            wb.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            wb.Credentials = new NetworkCredential(username, password);
            return Encoding.ASCII.GetString(wb.UploadData(url, Encoding.ASCII.GetBytes(postParams)));
        }

    }

}

